package netty.dubbo.server.server;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import netty.dubbo.api.bean.InvokeMessage;

import java.util.Map;

/**
 * @author: 程序员七哥
 * @date: 2021-12-19
 * @description: 服务器端处理类，和手写 RPC 框架的处理逻辑是一样的
 */
public class RpcServerHandler extends SimpleChannelInboundHandler {

    private Map<String, Object> registryMap;
    public RpcServerHandler(Map<String, Object> registerMap) {
        registryMap = registerMap;
    }

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, Object o) throws Exception {
        if (o instanceof InvokeMessage) {
            Object result = "该服务在注册中心没有找到";
            InvokeMessage message = (InvokeMessage) o;
            if (registryMap.containsKey(message.getClassName())) {
                final Object provider = registryMap.get(message.getClassName());
                result = provider.getClass().getMethod(message.getMethodName(),message.getParameterTypes())
                        .invoke(provider,message.getParameterValues());
            }
            channelHandlerContext.writeAndFlush(result);
            // 处理完本次调用则关闭当前连接
            channelHandlerContext.close();
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}
